﻿using HBKY.Shop.Common.Attributess;
using HBKY.Shop.Model.Enum;
using System;
using System.ComponentModel;
using System.Linq;

namespace HBKY.Shop.Common.Extension
{
    /// <summary>
    /// 枚举扩展
    /// </summary>
    public static class EnumExtension
    {
        public static string GetDescription(this Enum value)
        {
            if (value == null) return string.Empty;
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null) return Convert.ToInt32(value).ToString();
            var attribute = value.GetAttribute<DescriptionAttribute>();
            if (attribute != null) return attribute.Description;
            return name;
        }


        public static string GetSmallHump(this Enum value)
        {
            if (value == null) return string.Empty;
            var str = value.ToString();
            return str.Substring(0, 1).ToLower() + str.Substring(1);
        }

        

        public static string GetTag(this Enum obj)
        {
            string objName = obj.ToString();
            Type t = obj.GetType();
            System.Reflection.FieldInfo fi = t.GetField(Enum.GetName(t, obj));
            TagAttribute[] arrDesc = (TagAttribute[])fi.GetCustomAttributes(typeof(TagAttribute), false);
            return arrDesc[0].Name;
        }

        public static T GetAttribute<T>(this Enum value) where T : System.Attribute
        {
            Type type = value.GetType();
            var field = type.GetField(Enum.GetName(type, value));
            return (T) field.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        }

        /// <summary>
        /// 获取枚举key 值
        /// </summary>
        public static int Key(this Enum var)
        {
            return Convert.ToInt32(var);
        }
        public static string StrValue(this System.Enum @enum)
        {
            return @enum.Key().ToString();
        }
        public static bool ValueEqualTo(this System.Enum @enum, string value)
        {
            return @enum.StrValue() == value;
        }
    }
}